package com.tony.ai

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.ImageProxy
import androidx.camera.view.PreviewView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.tony.ai.camerax.CameraPreviewUtil

/**
 * 基类
 */
open abstract class BaseActivity : AppCompatActivity() {
    private val TAG = "BaseActivity"
    private var cameraUtil: CameraPreviewUtil? = null
    private var view_finder: PreviewView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestMyPermissions()
    }
    fun initCameraX(type: CameraPreviewUtil.AnalyzerType, view_finder: PreviewView) {
        setPreView(view_finder)
        view_finder.post {
            cameraUtil = CameraPreviewUtil(this@BaseActivity, view_finder, this)
            cameraUtil?.startPreview(type,object : CameraPreviewUtil.OnImageAnalysisResultListener {
                override fun onBitmapRotation(bitmap: Bitmap?, rotation: Int) {
                    super.onBitmapRotation(bitmap, rotation)
                    onGetBitmapResult(bitmap, rotation)
                }

                override fun onImageAnalysisResult(image: ImageProxy) {
                    super.onImageAnalysisResult(image)
                    onImageProxyResult(image)
                }
            })
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        cameraUtil?.stopPreview()
        Log.e(TAG, "onDestroy")
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        view_finder?.let { cameraUtil?.setTargetRotation(it) }
    }

    private fun setPreView(mViewFinder: PreviewView) {
        this.view_finder = mViewFinder
    }

    open fun onGetBitmapResult(bitmap: Bitmap?, rotation: Int) {}
    open fun onImageProxyResult(image: ImageProxy) {}


    //从相册中选择
    protected open fun requestMyPermissions() {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
            != PackageManager.PERMISSION_GRANTED
        ) {
            //没有授权，编写申请权限代码
            ActivityCompat.requestPermissions(
                this@BaseActivity,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                100
            )
        } else {
            Log.d(TAG, "requestMyPermissions: 有写SD权限")
        }
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
            != PackageManager.PERMISSION_GRANTED
        ) {
            //没有授权，编写申请权限代码
            ActivityCompat.requestPermissions(
                this@BaseActivity,
                arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                100
            )
        } else {
            Log.d(TAG, "requestMyPermissions: 有读SD权限")
        }
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.CAMERA
            )
            != PackageManager.PERMISSION_GRANTED
        ) {
            //没有授权，编写申请权限代码
            ActivityCompat.requestPermissions(
                this@BaseActivity,
                arrayOf(Manifest.permission.CAMERA),
                100
            )
        } else {
            Log.d(TAG, "requestMyPermissions: 相机")
        }
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.RECORD_AUDIO
            )
            != PackageManager.PERMISSION_GRANTED
        ) {
            //没有授权，编写申请权限代码
            ActivityCompat.requestPermissions(
                this@BaseActivity,
                arrayOf(Manifest.permission.RECORD_AUDIO),
                100
            )
        } else {
            Log.d(TAG, "requestMyPermissions: 录音")
        }
    }

    /**
     * 从相册中选择视频
     */
    open fun choiceVideo() {
        val i = Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(i, 66)
    }
    open fun choiceImage(){
        val i = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(i, 88)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 66 && resultCode == RESULT_OK && null != data) {
            val selectedVideo = data.data
            val filePathColumn = arrayOf(MediaStore.Video.Media.DATA)
            val cursor = contentResolver.query(
                selectedVideo!!,
                filePathColumn, null, null, null
            )
            cursor!!.moveToFirst()
            val columnIndex = cursor.getColumnIndex(filePathColumn[0])
            val path = cursor.getString(columnIndex)
            cursor.close()
            Log.e("path:", path)
            onVideoResult(path)
        }else if (requestCode == 88 && resultCode == RESULT_OK && null != data) {
            val selectedImage = data.data
            val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
            val cursor = contentResolver.query(
                selectedImage!!,
                filePathColumn, null, null, null
            )
            cursor!!.moveToFirst()
            val columnIndex = cursor.getColumnIndex(filePathColumn[0])
            val path = cursor.getString(columnIndex)
            cursor.close()
            Log.e("path:", path)
            onImageResult(path)
        }
        if (resultCode != RESULT_OK) {
            return
        }
    }

    open fun onImageResult(path: String?){}


    /**
     * 回调选中视频的路径
     * @param vidoPath
     */
     open fun onVideoResult(vidoPath: String?){}
}